import { Injectable } from '@angular/core';
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class RegionService {

  constructor(private http:Http) { }

  list(parentCode:string):Observable<any[]> {
    // 数据更新：https://github.com/modood/Administrative-divisions-of-China
    if((parentCode||'')=='') {
      return new Observable((observer) => {
        this.http.get('assets/data/region/provinces.json').map(res => res.json()).subscribe((data) => {
          observer.next(data)
          observer.complete()
        })
      })
    }else{
      return new Observable((observer)=>{
        this.http.get('assets/data/region/cities.json').map(res => res.json()).subscribe((data) => {
          let cityList = data.filter(item => item['parent_code']==parentCode)
          if(cityList.length) {
            observer.next(cityList)
            observer.complete()
          }else{
            this.http.get('assets/data/region/counties.json').map(res => res.json()).subscribe((data) => {
              let countyList = data.filter(item => item['parent_code']==parentCode)
              if(countyList.length) {
                observer.next(countyList)
                observer.complete()
              }else{
                observer.error('no such parentCode')
                observer.complete()
              }
            })
          }
        })
      })
    }
  }

}
